/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csse3004.GD.DA;

import csse3004.GD.Message;
import csse3004.GD.Poll;
import csse3004.GD.Question;
import csse3004.GD.WBUser.PollUsers;
import csse3004.GD.WBUser.WBUserService;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Logger;

/**
 *
 * @author Tom McNair - S41758984
 */
public class WBUserDA extends GenericDA implements WBUserService {
    private static final Logger m_logger = Logger.getLogger(LoginDA.class.getName());
        
    public ArrayList<Poll> getPolls(int userID) {
        String sql = "SELECT Poll.Poll_ID, Poll.Poll_Name, Poll.Public_Result, "
                + "Poll.Anonymous, Poll.Admin_ID "
                + "FROM Poll, Users, Participant, Participant_List "
                + "WHERE USERS.User_ID = PARTICIPANT.User_ID AND "
                + "Participant.List_ID = Participant_List.List_ID AND "
                + "Participant_List.Poll_ID = Poll.Poll_ID AND Users.User_ID = "
                + userID;
        
        m_logger.info(sql);
        
        ArrayList<Poll> pollArray = new ArrayList<Poll>();  
        Poll poll;
        
        try {
            ResultSet results = DatabaseQuery(sql);
            int i = 0;
            while (results.next()) {
                m_logger.info("Try Number: "+i);
                poll = new Poll();
                
                poll.setId(results.getInt("Poll_ID"));
                poll.setName(results.getString("Poll_Name"));
                m_logger.info("POLL NAME: "+poll.getName());
                if(results.getString("Public_Result").equals("Yes")) {
                    poll.setPublicResult();
                } else {
                    poll.setPrivateResult();
                }
                
                if(results.getString("Anonymous").equals("Yes")) {
                    poll.setAnonymous(true);
                } else {
                    poll.setAnonymous(false);
                }
                
                String sql2 = "SELECT * FROM Question WHERE Poll_ID = "+results.getInt("Poll_ID");
                ResultSet results2 = DatabaseQuery(sql2);
                if (results2.next()) {
                    poll.setFirstQuestionID(results2.getInt("Question_ID"));
                }
                
                pollArray.add(poll);
            }
        
            return pollArray;
            
        } catch (Exception ex) {
            m_logger.info("getPolls() failed\n");
            m_logger.info(ex.toString());
        }
        return null;
    }
    
    public Poll getPoll(int pollID) {
        String sql = "SELECT * FROM Poll WHERE Poll_ID = "+pollID;
        
        Poll poll = new Poll();
        
        try {
            ResultSet results = DatabaseQuery(sql);
            
            if (results.next()) {
                
                poll.setId(results.getInt("Poll_ID"));
                poll.setName(results.getString("Poll_Name"));
                
                if(results.getString("Public_Result").equals("Yes")) {
                    poll.setPublicResult();
                } else {
                    poll.setPrivateResult();
                }
                
                if(results.getString("Anonymous").equals("Yes")) {
                    poll.setAnonymous(true);
                } else {
                    poll.setAnonymous(false);
                }
            }
        
            return poll;
            
        } catch (Exception ex) {
            m_logger.info("getPoll() failed\n");
            m_logger.info(ex.toString());
        }
        return null;
    }
    
    public boolean answerMC(int answerID, int preference, int questionID, int userID) {
        int responseID = getNextID("MC_Response");
        String sql = "INSERT INTO MC_Response VALUES("+responseID+", "+answerID+", "+preference+", "+questionID+", "+userID+")";
        
        m_logger.info(sql);
        try {
            if (DatabaseInsert(sql)) {
                m_logger.info("Yay");
                return true;
            } else {
                return false;
            }
        } catch(Exception ex) {
            m_logger.info("answerMC() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
    }
    public boolean answerSR(String response, int questionID, int userID) {
        int responseID = getNextID("SR_Response");
        String sql = "INSERT INTO SR_Response VALUES("+responseID+", '"+response+"', "+questionID+", "+userID+")";
        
        m_logger.info(sql);
        try {
            if (DatabaseInsert(sql)) {
                m_logger.info("Yay");
                return true;
            } else {
                return false;
            }
        } catch(Exception ex) {
            m_logger.info("answerMC() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
    }
    
    public ArrayList<Message> getMessages(int userID) {
        String sql = "SELECT * FROM Message WHERE Receiver_ID = "+userID+" AND Deleted = 'No'";
        ArrayList<Message> messages = new ArrayList<Message>();
        Message message = new Message();
        
        try {
            ResultSet results = DatabaseQuery(sql);
            while(results.next()) {
                message.setSender(results.getInt("Sender_ID"));
                message.setReceiver(userID);
                message.setHeader(results.getString("Header"));
                message.setBody(results.getString("Text"));
                if (results.getString("Read").equals("Yes")) {
                    message.setRead(true);
                } else {
                    message.setRead(false);
                }
                if (results.getString("Private").equals("Yes")) {
                    message.setPrivateMessage(true);
                } else {
                    message.setPrivateMessage(false);
                }
                messages.add(message);
            }
            return messages;
        } catch (Exception ex) {
            m_logger.info("getMessages() failed\n");
            m_logger.info(ex.toString());
            return null;
        }
    }

    public boolean setMessageRead(int messageID, boolean read) {
        String sql;
        
        if (read) {
            sql = "UPDATE Message SET Read = 'Yes' WHERE Message_ID = "+messageID;
        } else {
            sql = "UPDATE Message SET Read = 'No' WHERE Message_ID = "+messageID;
        }
        try {
            if (!DatabaseInsert(sql)) {
                return false;
            }
        } catch (Exception ex) {
            m_logger.info("setMessageRead() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
        return true;
    }
    
    public final int getNextQuestion(int pollID, boolean isNext, int currentQuestion) {
        String sql = "SELECT * FROM Question WHERE Poll_ID = "+pollID+" AND Deleted = 'No' AND Overwritten = 'No'";
        m_logger.info(sql);
        
        m_logger.info("Current Question ID: "+currentQuestion);
        try {            
            ResultSet results = DatabaseQuery(sql);
            while (results.next()) {
                if (results.getInt("Question_ID") == currentQuestion) {
                    if (isNext) {
                        if (results.next()) {
                            m_logger.info("Question ID:"+results.getInt("Question_ID"));
                            return results.getInt("Question_ID");
                        }
                            m_logger.info("-1\n");
                            return -1;                        
                    } else {
                         if (results.previous()) {
                            m_logger.info("Question ID:"+results.getInt("Question_ID"));
                            return results.getInt("Question_ID");
                        } 
                            m_logger.info("-1\n");
                            return -1;                        
                    }
                }
            }
        } catch (Exception ex) {
            m_logger.info("getNextQuestion() failed\n");
            m_logger.info(ex.toString());
            return -1;
        }
        return 1;
    }
    
        public final boolean sendFeedback(String feedback, int questionID){
        int feedbackID = getNextID("Feedback");
        String sql = "INSERT INTO Feedback VALUES("+feedbackID+", '"+feedback+"', "+questionID+")";
        m_logger.info(sql);
        try {
            if (DatabaseInsert(sql)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            m_logger.info("sendFeedback() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
    }
        
    public ArrayList<PollUsers> getActiveUsers(int pollID) {
        String sql = "SELECT Users.User_ID, Users.Username from Users, Participant, Participant_List WHERE Users.User_ID = Participant.User_ID AND Participant.List_ID = Participant_List.List_ID"
                + " AND Participant_List.Poll_ID =" + pollID;
        ArrayList<PollUsers> activeUsers = new ArrayList<PollUsers>();
        PollUsers activeUser;
        
        try {
            ResultSet results = DatabaseQuery(sql);
            while (results.next()) {
                activeUser = new PollUsers();
                activeUser.setUserID(results.getInt("User_ID"));
                activeUser.setUsername(results.getString("Username"));
                activeUsers.add(activeUser);
            }
            return activeUsers;
        } catch (Exception ex) {
            m_logger.info("getNextQuestion() failed\n");
            m_logger.info(ex.toString());
            return null;
        }
    }
}
